package com.director.spring;

import com.director.core.DirectConfiguration;
import com.director.core.Provider;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Writer;

/**
 * @author Simone Ricciardi
 * @version 1.0, 11/07/2010
 */
public class DirectRouterFilter extends OncePerRequestFilter {

   private DirectConfiguration configuration;

   @Required
   public void setConfiguration(DirectConfiguration configuration) {
      this.configuration = configuration;
   }

   @Override
   protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
      String providerId = request.getParameter(this.configuration.getProviderParamName());
      String formattedOutput;
      if(providerId != null) {
         Provider provider = this.configuration.getProvider(providerId);
         formattedOutput = provider.process(request);
      } else {
         formattedOutput = this.configuration.getFormattedApi();
      }
      this.applyHeaderConfiguration(response);
      Writer writer = response.getWriter();
      writer.append(formattedOutput);
      writer.flush();
   }

   private void applyHeaderConfiguration(HttpServletResponse response) {
      response.setContentType("text/plain");
      response.setCharacterEncoding("UTF-8");
      response.setHeader("Transfer-Encoding", "chunked");
      response.setHeader("Content-Disposition", "inline");
   }
}
